#!/bin/bash
# =============================================
# 自动检查和修复系统限制配置脚本
# 版本: 1.0
# =============================================

echo "🚀 开始自动检查和修复系统限制配置..."
echo "=========================================="

# 检查当前用户
echo "📋 当前用户: $(whoami)"
echo "📋 当前时间: $(date)"
echo ""

# 1. 备份原始配置文件
echo "📦 备份配置文件中..."
sudo cp /etc/sysctl.conf /etc/sysctl.conf.backup.$(date +%Y%m%d)
sudo cp /etc/security/limits.conf /etc/security/limits.conf.backup.$(date +%Y%m%d)
echo "✅ 配置文件备份完成"

# 2. 添加优化参数
echo "⚡ 添加优化参数..."
sudo tee -a /etc/sysctl.conf << 'EOL'

fs.file-max = 600000
net.core.rmem_max = 67108864
net.core.wmem_max = 67108864
net.core.netdev_max_backlog = 250000
net.core.somaxconn = 4096
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.ip_local_port_range = 10000 65000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_mem = 25600 51200 102400
net.ipv4.tcp_rmem = 4096 87380 67108864
net.ipv4.tcp_wmem = 4096 65536 67108864
net.ipv4.tcp_mtu_probing = 1
net.ipv4.tcp_congestion_control = hybla
net.ipv4.tcp_max_orphans = 100000
net.nf_conntrack_max = 1000000
net.netfilter.nf_conntrack_tcp_timeout_established = 1200
fs.file-max = 1000000
EOL

# 3. 配置 limits.conf
echo "🔧 配置用户限制..."
sudo tee -a /etc/security/limits.conf << 'EOL'
# ===== 全局文件描述符限制 =====
* soft nofile 100000
* hard nofile 100000
root soft nofile 100000
root hard nofile 100000
EOL

# 4. 配置 systemd
echo "🔄 配置 systemd 服务限制..."
sudo sed -i '/DefaultLimitNOFILE/d' /etc/systemd/system.conf
echo "DefaultLimitNOFILE=100000" | sudo tee -a /etc/systemd/system.conf

# 5. 确保 PAM 配置
echo "🔐 检查 PAM 配置..."
for pam_file in /etc/pam.d/sshd /etc/pam.d/login /etc/pam.d/common-session; do
    if [ -f "$pam_file" ]; then
        if ! grep -q "pam_limits" "$pam_file"; then
            echo "session    required   pam_limits.so" | sudo tee -a "$pam_file"
            echo "✅ 已添加 pam_limits 到 $pam_file"
        fi
    fi
done

# 6. 立即生效
echo "⚡ 应用配置立即生效..."
sudo sysctl -p
ulimit -n 100000

# 7. 重启相关服务
echo "🔄 重启相关服务..."
sudo systemctl daemon-reload
sudo systemctl restart sshd 2>/dev/null || true

# 8. 验证配置
echo ""
echo "✅ 配置完成！验证结果："
echo "=========================================="
echo "📊 当前 ulimit -n: $(ulimit -n)"
echo "📊 当前 ulimit -Sn: $(ulimit -Sn)"
echo "📊 当前 ulimit -Hn: $(ulimit -Hn)"
echo "📊 系统总限制: $(cat /proc/sys/fs/file-max)"
echo "📊 SYN Backlog: $(cat /proc/sys/net/ipv4/tcp_max_syn_backlog)"
echo "📊 SOMAXCONN: $(cat /proc/sys/net/core/somaxconn)"
echo ""
EOF